#include <brpc/server.h>
#include <brpc/controller.h>
#include <google/protobuf/stubs/common.h>
#include "echo.pb.h"
#include <memory>
#include<butil/logging.h>
#include"../../etcd/etcd.hpp"

class EchoSer : public example::EchoService // 继承抽象接口类; EchoService 继承自 google::protobuf::Service
{
public:
    EchoSer() {}
    ~EchoSer() {}

    // 重写
    //  ::google::protobuf::RpcController* controller 抽象接口类
    void Echo(::google::protobuf::RpcController *controller,
              const ::example::EchoRequest *request,
              ::example::EchoResponse *response,
              ::google::protobuf::Closure *done) override
    {
        // RAII: Call Run() of the closure on destruction.
        brpc::ClosureGuard cg_done(done);

        std::string in = request->message();
        std::cout << "收到：" << in << std::endl;
        response->set_message(in);
    }
};

int main()
{
    // 构建服务器实例: 服务器将客户端的请求分派给已注册的服务将响应发送回客户端
    std::unique_ptr<brpc::Server> service = std::make_unique<brpc::Server>();
    // 具体服务实例化
    EchoSer echo_ser;
    brpc::ServiceOptions ops; // 服务配置，比如：最大超时时间，线程数，......
    // service.AddService(&echo_ser, ops);
    if (service->AddService(&echo_ser, ops) == -1)
    {
        std::cout << "服务添加失败！" << std::endl;
        return -1;
    }
    std::cout << "服务添加成功！" << std::endl;

    // 启动服务: 绑定 ip和port
    brpc::ServerOptions sops; // 配置选项
    if (service->Start("0.0.0.0:8080", &sops) != 0) {
        std::cout << "服务器启动失败！" << std::endl;
        return -1;
    }

    // 服务注册到 etcd 服务器
    init_mylogger(false, "test", "", 0, false);
    ns_etcd_client::Register rt("127.0.0.1:2379", "./Echo/node1", "127.0.0.1:8080");

    service->RunUntilAskedToQuit();
    return 0;
}